<template>
  <div>
    <div class="page-header">
      <h1 class="page-title">药品追溯</h1>
    </div>

    <!-- Search Section -->
    <a-card class="mb-16">
      <a-form layout="inline">
        <a-form-item label="RFID ID">
          <a-input-search
            v-model:value="rfidId"
            placeholder="请输入16位RFID标识符"
            style="width: 240px"
            @search="searchTrace"
            enter-button
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" :loading="loading" @click="searchTrace">
            查询追溯
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <div v-if="traceData">
      <!-- Medicine Info -->
      <a-card title="药品信息" class="mb-16">
        <a-descriptions bordered :column="{ xxl: 4, xl: 3, lg: 3, md: 2, sm: 1, xs: 1 }">
          <a-descriptions-item label="RFID ID">
            <a-tag color="blue">{{ medicineInfo.rfid_id }}</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="药品名称">{{ medicineInfo.name }}</a-descriptions-item>
          <a-descriptions-item label="规格">{{ medicineInfo.spec }}</a-descriptions-item>
          <a-descriptions-item label="生产厂家">{{ medicineInfo.manufacturer }}</a-descriptions-item>
          <a-descriptions-item label="生产批次">
            <a-tag color="cyan">{{ medicineInfo.batch }}</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="生产日期">{{ formatDate(medicineInfo.production_date) }}</a-descriptions-item>
          <a-descriptions-item label="有效期至">
            {{ formatDate(medicineInfo.expiry_date) }}
            <a-tag v-if="isExpired(medicineInfo.expiry_date)" color="red">已过期</a-tag>
            <a-tag v-else color="green">有效期内</a-tag>
          </a-descriptions-item>
        </a-descriptions>
      </a-card>

      <!-- Timeline -->
      <a-card title="完整追溯记录">
        <div class="timeline-container">
          <a-timeline mode="alternate">
            <a-timeline-item 
              v-for="(event, index) in sortedEvents" 
              :key="index"
              :color="getEventColor(event.event_type)"
            >
              <template #dot>
                <component 
                  :is="getEventIcon(event.event_type)" 
                  style="font-size: 16px;" 
                />
              </template>
              <div class="timeline-content">
                <div class="timeline-title">
                  <span class="event-type">
                    <a-tag :color="getEventColor(event.event_type)">
                      {{ getEventTypeText(event.event_type) }}
                    </a-tag>
                  </span>
                  <span class="event-time">{{ formatDateTime(event.timestamp) }}</span>
                </div>
                <div class="timeline-detail">
                  <p><strong>地点：</strong>{{ event.location }}</p>
                  <p><strong>操作人员：</strong>{{ event.operator }}</p>
                  <p v-if="event.notes"><strong>备注：</strong>{{ event.notes }}</p>
                </div>
              </div>
            </a-timeline-item>
          </a-timeline>
        </div>
      </a-card>

      <!-- Actions -->
      <div class="action-container">
        <a-button type="primary" @click="showAddEventModal">
          <template #icon><plus-outlined /></template>
          添加追溯事件
        </a-button>
        <a-button @click="printTrace">
          <template #icon><printer-outlined /></template>
          打印追溯记录
        </a-button>
        <a-button @click="exportTrace">
          <template #icon><download-outlined /></template>
          导出追溯数据
        </a-button>
      </div>
    </div>

    <div v-else-if="!loading && searched" class="empty-state">
      <a-empty description="未找到药品追溯记录" />
      <a-button type="primary" @click="goToMedicineManagement">
        前往药品管理
      </a-button>
    </div>

    <!-- Add Event Modal -->
    <a-modal
      v-model:visible="addEventModalVisible"
      title="添加追溯事件"
      @ok="handleAddEventOk"
      :confirmLoading="confirmLoading"
    >
      <a-form
        :model="eventForm"
        :rules="rules"
        ref="formRef"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="RFID ID" name="rfid_id">
          <a-input v-model:value="eventForm.rfid_id" disabled />
        </a-form-item>
        <a-form-item label="事件类型" name="event_type">
          <a-select v-model:value="eventForm.event_type" placeholder="请选择事件类型">
            <a-select-option value="storage">入库</a-select-option>
            <a-select-option value="transport">运输</a-select-option>
            <a-select-option value="sale">销售</a-select-option>
            <a-select-option value="verification">验证</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="事件地点" name="location">
          <a-input v-model:value="eventForm.location" placeholder="请输入事件地点" />
        </a-form-item>
        <a-form-item label="操作人员" name="operator">
          <a-input v-model:value="eventForm.operator" placeholder="请输入操作人员" />
        </a-form-item>
        <a-form-item label="备注信息" name="notes">
          <a-textarea v-model:value="eventForm.notes" placeholder="请输入备注信息" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import moment from 'moment'
import { message } from 'ant-design-vue'
import api from '@/services/api'
import {
  PlusOutlined,
  PrinterOutlined,
  DownloadOutlined,
  ExperimentOutlined,
  InboxOutlined,
  CarOutlined,
  ShoppingOutlined,
  SafetyCertificateOutlined,
  ScanOutlined
} from '@ant-design/icons-vue'

// Types
interface TraceEvent {
  rfid_id: string
  event_type: string
  location: string
  operator: string
  notes: string
  timestamp: string
}

interface TraceData {
  rfid_id: string
  events: TraceEvent[]
}

interface Medicine {
  rfid_id: string
  name: string
  spec: string
  manufacturer: string
  batch: string
  production_date: string
  expiry_date: string
  created_at: string
  verification_hash: string
}

// State
const router = useRouter()
const route = useRoute()
const rfidId = ref('')
const loading = ref(false)
const searched = ref(false)
const traceData = ref<TraceData | null>(null)
const medicineInfo = ref<Medicine>({} as Medicine)
const addEventModalVisible = ref(false)
const confirmLoading = ref(false)
const formRef = ref(null)

// Form state
const eventForm = reactive({
  rfid_id: '',
  event_type: 'storage',
  location: '',
  operator: '管理员',
  notes: ''
})

// Form validation rules
const rules = {
  event_type: [{ required: true, message: '请选择事件类型', trigger: 'change' }],
  location: [{ required: true, message: '请输入事件地点', trigger: 'blur' }],
  operator: [{ required: true, message: '请输入操作人员', trigger: 'blur' }]
}

// Computed
const sortedEvents = computed(() => {
  if (!traceData.value || !traceData.value.events) return []
  
  return [...traceData.value.events].sort((a, b) => {
    return new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
  })
})

// Methods
const searchTrace = async () => {
  if (!rfidId.value || rfidId.value.length !== 16) {
    message.warning('请输入16位RFID标识符')
    return
  }

  loading.value = true
  searched.value = true
  
  try {
    // Get trace data
    const startTime = Date.now()
    const response = await api.getTraceHistory(rfidId.value)
    const traceResponse = response.data
    
    if (traceResponse) {
      traceData.value = traceResponse
      
      // Get medicine info
      const medicineResponse = await api.getMedicineByRfid(rfidId.value)
      medicineInfo.value = medicineResponse.data
      
      const elapsed = Date.now() - startTime
      
      // Check if meets performance requirement
      if (elapsed <= 3000) {
        message.success(`查询成功，用时 ${elapsed}ms`)
      } else {
        message.warning(`查询成功，但用时 ${elapsed}ms 超过了预期的3秒`)
      }
    } else {
      traceData.value = null
      message.warning('未找到该RFID对应的追溯信息')
    }
  } catch (error) {
    console.error('Failed to fetch trace data:', error)
    message.error('查询失败，请检查RFID ID是否正确')
    traceData.value = null
  } finally {
    loading.value = false
  }
}

const formatDate = (dateStr: string | undefined): string => {
  if (!dateStr) return ''
  return moment(dateStr, 'YYYYMMDD').format('YYYY-MM-DD')
}

const formatDateTime = (dateTimeStr: string | undefined): string => {
  if (!dateTimeStr) return ''
  return moment(dateTimeStr).format('YYYY-MM-DD HH:mm:ss')
}

const isExpired = (dateStr: string | undefined): boolean => {
  if (!dateStr) return false
  return moment(dateStr, 'YYYYMMDD').isBefore(moment(), 'day')
}

const getEventTypeText = (type: string): string => {
  const types: Record<string, string> = {
    'production': '生产',
    'storage': '入库',
    'transport': '运输',
    'sale': '销售',
    'verification': '验证',
    'scan': '扫描'
  }
  return types[type] || type
}

const getEventColor = (type: string): string => {
  const colors: Record<string, string> = {
    'production': 'blue',
    'storage': 'cyan',
    'transport': 'purple',
    'sale': 'green',
    'verification': 'orange',
    'scan': 'geekblue'
  }
  return colors[type] || 'blue'
}

const getEventIcon = (type: string) => {
  const icons: Record<string, any> = {
    'production': ExperimentOutlined,
    'storage': InboxOutlined,
    'transport': CarOutlined,
    'sale': ShoppingOutlined,
    'verification': SafetyCertificateOutlined,
    'scan': ScanOutlined
  }
  return icons[type] || ExperimentOutlined
}

const showAddEventModal = () => {
  eventForm.rfid_id = rfidId.value
  addEventModalVisible.value = true
}

const handleAddEventOk = async () => {
  try {
    if (!formRef.value) return
    
    // 使用可选链和类型断言
    const form = formRef.value as any;
    if (form.validate) {
      await form.validate();
    }
    
    confirmLoading.value = true
    
    // Add trace event
    const startTime = Date.now()
    await api.addTraceEvent(eventForm)
    const elapsed = Date.now() - startTime
    
    message.success(`追溯事件记录成功，用时 ${elapsed}ms`)
    addEventModalVisible.value = false
    
    // Refresh trace data
    await searchTrace()
  } catch (error) {
    console.error('Failed to add trace event:', error)
    message.error('添加追溯事件失败，请检查输入')
  } finally {
    confirmLoading.value = false
  }
}

const goToMedicineManagement = () => {
  router.push('/medicine-management')
}

const printTrace = () => {
  message.success('正在准备打印')
  window.print()
}

const exportTrace = () => {
  if (!traceData.value) return
  
  const dataStr = JSON.stringify(traceData.value, null, 2)
  const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr)
  
  const exportFileDefaultName = `trace_${rfidId.value}_${moment().format('YYYYMMDD_HHmmss')}.json`
  
  const linkElement = document.createElement('a')
  linkElement.setAttribute('href', dataUri)
  linkElement.setAttribute('download', exportFileDefaultName)
  linkElement.click()
  
  message.success('追溯数据导出成功')
}

// Lifecycle hooks
onMounted(() => {
  // Check if rfid was passed in query params
  const queryRfid = route.query.rfid as string
  if (queryRfid) {
    rfidId.value = queryRfid
    searchTrace()
  }
})
</script>

<style scoped>
.page-header {
  margin-bottom: 24px;
}

.timeline-container {
  padding: 20px;
  max-height: 600px;
  overflow-y: auto;
}

.timeline-content {
  padding: 8px;
  border-radius: 4px;
  background-color: #f9f9f9;
  box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}

.timeline-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.event-type {
  font-weight: bold;
}

.event-time {
  color: #999;
  font-size: 12px;
}

.timeline-detail {
  font-size: 14px;
}

.timeline-detail p {
  margin-bottom: 4px;
}

.action-container {
  display: flex;
  gap: 16px;
  margin-top: 24px;
  margin-bottom: 24px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 48px 0;
}

.empty-state .ant-btn {
  margin-top: 16px;
}

@media print {
  .action-container,
  .page-header,
  .ant-layout-header,
  .ant-layout-sider {
    display: none !important;
  }
  
  .timeline-container {
    max-height: none;
    overflow: visible;
  }
}
</style> 